#!/usr/bin/python3
import json
import random

import requests

COMMAND_DICT = {
    "start-update": "auto-release start",
    "get-requires": "auto-release get-requires {releaseIssueID}",
    "check-status": "auto-release check-issues-status {releaseIssueID}",
    "test-ok": "auto-release check-release {releaseIssueID}",
    "check-ok": "auto-release release-update-pkg $releaseIssueID $timestamp auto-release",
    "check-ok": "upload-update-list $releaseIssueID",
    "check-ok and cvrf-ok": "auto-release release-update-sa $releaseIssueID $timestamp",
    "add-cve": "auto-release {releaseIssueID} add-cve {modifyIssueID}",
    "add-bugfix": "auto-release {releaseIssueID} add-bugfix {modifyIssueID}",
    "add-requires": "auto-release {releaseIssueID} add-requires {modifyIssueID}",
    "add-test ": "auto-release {releaseIssueID} add-test {modifyIssueID}",
    "delete-cve": "auto-release {releaseIssueID} delete-cve {modifyIssueID}",
    "delete-bugfix": "auto-release {releaseIssueID} delete-bugfix {modifyIssueID}",
    "delete-requires": "auto-release {releaseIssueID} delete-requires {modifyIssueID}",
    "delete-test ": "auto-release {releaseIssueID} delete-test {modifyIssueID}",
}


class GiteeIssue:
    """
    download patch file
    """
    # TODO 优化的改进项
    access_token = [
        "1b876f46031e167517765b2f0861fff6"
    ]
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW 64; rv:50.0) "
                      "Gecko/20100101 Firefox/50.0"
    }

    def __init__(self):
        self.issues_id = []
        self.issue_url = "https://gitee.com/api/v5/enterprises/open_euler/issues/{}"
        self.update_issue_url = "https://gitee.com/api/v5/repos/{owner}/issues/{number}"
        self.create_issue_url = "https://gitee.com/api/v5/repos/{owner}/issues"
        self.install_build_issue = []
        self.issue_status_dict = {}
        self.is_open = False

    def get_issue_state(self, issues_id):
        issues_id = issues_id if isinstance(issues_id, list) else [issues_id]
        for issue_id in issues_id:
            response_info = self.get_issue_content(self.issue_url.format(issue_id))
            self._parse_issue_comment(response_info, issue_id)

    def get_issue_content(self, issue_url):
        try:
            response = requests.get(issue_url, params={
                "access_token": self.access_token[random.randint(0, len(self.access_token) - 1)]}, timeout=2,
                                    headers=self.headers)
        except Exception:
            print("链接超时")
            return []
        if response.status_code != 200:
            return []
        try:
            response = response.json()
        except json.JSONDecodeError:
            response = list()
        return response

    def _parse_issue_comment(self, issue_info, issue_id):
        issue_state = {}
        try:
            issue_state[issue_id] = issue_info["state"]
        except (TypeError, KeyError):
            print("Something unexpected happened, please check and try again")
            return
        if issue_info["state"] == "open":
            self.is_open = True
        self.install_build_issue.append(issue_state)

    def check_issue_state(self, issues_id):
        self.get_issue_state(issues_id)
        if self.is_open:
            self.issue_status_dict["overall_status"] = "open"
        else:
            self.issue_status_dict["overall_status"] = "closed"
        self.issue_status_dict["install_build_issue"] = self.install_build_issue
        return self.issue_status_dict

    def create_install_build_issue(self):
        # TODO
        if check_install_build:
            return True
        if self.get_issue_content():
            self.update_issue()
        else:
            self.create_issue()

    def update_issue(self, repository, issue_id):
        # self.update_issue_url = "https://gitee.com/api/v5/repos/{}/issues/{}".format(repository, )
        self.update_issue_url = "https://gitee.com/api/v5/repos/MementoMoriCheng/issues/{}".format(issue_id)
        data = {"access_token": self.access_token[random.randint(0, len(self.access_token) - 1)], "repo": repository,
                "state": "open", "body": "nihao ,gousheng"}
        try:
            response = requests.patch(url=self.update_issue_url, data=data, headers=self.headers)
        except Exception:
            print("链接超时")
            return False
        print(response.status_code)
        if response.status_code == 200:
            return True

        return False

    def create_issue(self, repository):
        # self.create_issue_url = "https://gitee.com/api/v5/repos/{}/issues".format(repository)
        self.create_issue_url = "https://gitee.com/api/v5/repos/MementoMoriCheng/issues"
        data = {"access_token": self.access_token[random.randint(0, len(self.access_token) - 1)],
                "repo": repository, "title": "test123", "body": "123456,123456"}
        try:
            response = requests.post(url=self.create_issue_url, data=data, headers=self.headers)
        except Exception:
            print("链接超时")
            return False
        print(response.status_code)
        if response.status_code == 404:
            return False
        return True

    # def operation_issue(self, url, data):
    #     try:
    #         response = requests.post(url=url, data=data, headers=self.headers)
    #     except Exception:
    #         print("链接超时")
    #         return False
    #     print(response.status_code)
    #     if response.status_code == 200:
    #         return True
    #
    #     return False


a = GiteeIssue()
# print(a.check_issue_state(["I1TTNK", "I1EMYU"]))
# print(a.create_issue("ticket_12306"))
print(a.update_issue("ticket_12306", "I3XN77"))
# response = requests.post("https://gitee.com/api/v5/repos/MementoMoriCheng/issues",
#                          data={"access_token": "1b876f46031e167517765b2f0861fff6", "repo": "",
#                                "title": "test", "body": "123456,123456"})
# print(response.status_code)
# print(response.content)


import functools

permission_info = {
    "version_manager": ["/start-update", ],
    "safety_committee": [
        "/add cve ",
        "/delete cve",
        "/cve-ok",
        "/check-ok",
        "/cvrf-ok",
    ],
    "developer": [
        "/add bugfix",
        "/delete bugfix",
        "/bugfix-ok",
        "/check-status",
        "/get-requires",
    ],
    "tester": ["/test-ok"],
    "tc": ["/check-ok"],
    "release": ["/check-ok"],
    "qa": ["/check-ok"]
}


def users_check(user, comment):
    """
    Determine whether the user requesting the operation has relevant permissions
    Args:
        user: user id
        comment:

    Returns:

    """

    def wrapper(func):
        @functools.wraps(func)
        def inner(*args, **kwargs):
            try:
                if comment not in permission_info[user]:
                    print("No operation permission, please contact the administrator")
                    return
            except Exception:
                print("Something unexpected happened, please check and try again")
                return
            return func(*args, **kwargs)

        return inner

    return wrapper

# user = input()
# comment = input()
#
#
# @users_check(user=user, comment=comment)
# def admin(*args):
#     print("success")
#
#
# admin()
